//牌价刷新定时任务，当后台服务断开时，停止定时任务
var interval;
//页面初始化时为false,需要加载牌价，当牌价加载完后，只更新价格(用于判断是否是更新牌价，还是加载牌价tr
var flag = false;

//自动加载
$(function () {
    //获取牌价
    getspotPrice();
    //自动更新牌价
    interval = setInterval(function () {
        getspotPrice();
    }, 1000);
    //将牌价置灰定时任务
    setInterval(function () {
        $(".tdprice").css("color", "black");//移除刷新
    }, 8000);
});

function getspotPrice() {
    $.ajax({
        url: "spotPrice",
        type: 'post',
        dataType: 'json',
        async: false,
        success: function (msg) {
            for (var i = 0; i < msg.length; i++) {
                createTr(msg[i],i);
            }
            //牌价加载完成后，设置为true，后续只能更新价格
            flag = true;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //后台停服务时，暂停定时任务
            clearInterval(interval);
        }
    });
};

//自选按钮
function addSelect(btn) {
    var $tds = $(btn).parent().siblings();
    var td1 = $tds.eq(0).html();
    $.ajax({
        url: "addSelect",
        type: "post",
        async: false,
        data: {"indexName": td1},
        success: function (respResult) {
            // alert("添加自选成功");
        },
        error: function (respResult) {
            alert('失败');
        }
    });
}


function createTr(data,i) {
    var indexName = data.indexName;
    var ask = data.ask;
    var bid = data.bid;
    var strLine = '<tr class='+"str_"+indexName+'>';
    if (i % 2 != 0) {
        strLine = '<tr style="background:#0000000A" class='+"str_"+indexName+'>';
    }
    var $tr =
            // $('<tr class="str_"'+indexName+'>'+
            $(strLine+
            '<td   style="display:none">' + indexName + '</td>' +
            '<td   ><a style="width:10px;"  href="" >' + indexName + '</a></td>' +
            '<td  align="center" class ="tdprice" id=' + indexName + '_ask' + '>' + ask + '</td>' +
            '<td   align="center" class ="tdprice"  id=' + indexName + '_bid' + '>' + bid + '</td>' +
            '<td    align="center"><input type="button" style="background:#FAEBD7" onclick="addSelect(this);" value="+"/></td>' +
            '</tr>');
    //追加到tbody下
    if (flag == false) {
        $("#page1Tbody").append($tr);
    } else {
        var class1 = '.str_' + indexName;
        var askid = indexName + '_ask';
        var bidid = indexName + '_bid';
        var askIdValue = $("#" + askid).text()
        var bidIdValue = $("#" + bidid).text()
        $("#" + askid).text(ask);
        $("#" + bidid).text(bid);
        if (askIdValue < ask) {
            $("#" + askid).css("color", "red");
            $("#" + bidid).css("color", "red");
        } else if (askIdValue > ask) {
            $("#" + askid).css("color", "green");
            $("#" + bidid).css("color", "green");
        }
    }
}


